<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    RuleController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    RuleController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Admin_RuleController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * The auth data
     * @var Zend_Auth
     */
    protected $_auth;

    /**
     * The AJAX flag
     * @var boolean
     */
    protected $_isAjax;

    /**
     * The language ID
     * @var integer
     */
    protected $_languageId;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Set admin layout
        $this->_helper->layout()->setLayout('admin');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $this->view->language = $locale->getLanguage();

        // Get language ID
        $languageModel = new Admin_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());

        // Chect authenctication
        $this->_auth = Zend_Auth::getInstance();
        if (!$this->_auth->hasIdentity()) {
            $this->_redirect('/' . $this->view->language . '/admin/login');
        }

        // Check AJAX
        if ($this->getRequest()->isXmlHttpRequest()) {

            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->_isAjax = true;
        } else {
            // Get current url without language
            $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

            $this->view->shopName = Zend_Registry::get('config')->shopName;
        }
    }

    /**
     * Action for index
     */
    public function indexAction()
    {
        // Initialize filters for orders
        $categoryName = null;
        $manufacturerName = null;
        $productName = null;
        $markupFrom = null;
        $markupTo = null;
        $updatedFrom = null;
        $updatedTo = null;
        $priorityFrom = null;
        $priorityTo = null;
        $updatedFrom = null;
        $updatedTo = null;
        $sort = null;
        $direction = null;
        $page = 1;
        $rowCount = 20;

        // Initialize form for filter
        $form = new Admin_Model_FormPriceRules();
        $form->setAction('/' . $this->view->language . '/admin/price_rule/index');

        // Get request params
        if ($this->getRequest()->isPost() && $form->isValid($data = $this->_request->getPost())) {
            $categoryName = $data['category_name'];
            $manufacturerName = $data['manufacturer_name'];
            $productName = $data['product_name'];
            $markupFrom = $data['markup_from'];
            $markupTo = $data['markup_to'];
            $priorityFrom = $data['priority_from'];
            $priorityTo = $data['priority_to'];
            $updatedFrom = $data['updated_from'];
            $updatedTo = $data['updated_to'];
            $sort = $data['sort'];
            $direction = $data['direction'];
            $page = $data['page'];
            $rowCount = $data['rows'];
        }

        // Get invoices from database
        $priceRuleModel = new Admin_Model_PriceRule();
        $this->view->priceRules = $priceRuleModel->getAllByFilter($categoryName, $manufacturerName, $productName, $markupFrom, $markupTo, $priorityFrom, $priorityTo, $updatedFrom, $updatedTo, $this->_languageId, $sort, $direction, $page, $rowCount);

        // Get page count
        $recordsCount = $priceRuleModel->getCountByFilter($categoryName, $manufacturerName, $productName, $markupFrom, $markupTo, $priorityFrom, $priorityTo, $updatedFrom, $updatedTo, $this->_languageId);
        $form->records_count->setValue($recordsCount);
        $form->pages_count->setValue(ceil($recordsCount / $rowCount));

        // Add form to view
        $this->view->formPriceRules = $form;

        // Render AJAX content
        if ($this->_isAjax) {
            echo $this->view->render('/rule/_filtered.phtml');
        }

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Action for edit
     */
    public function editAction()
    {
        // Initialize price rule form
        $form = new Admin_Model_FormPriceRule(array('languageId' => $this->_languageId));
        $form->setAction('/' . $this->view->language . '/admin/price_rule/save/');

        // Get id of price rule
        $id = $this->_request->getParam('id');
        if ($id) {
            // Prepare priceRule for editing
            $priceRuleModel = new Admin_Model_PriceRule();
            $priceRule = $priceRuleModel->getById($id);
            if ($priceRule) {
                $form->id->setValue($priceRule->id);
                $form->category->setValue($priceRule->category_id);
                $form->manufacturer->setValue($priceRule->manufacturer_id);
                $form->product->setValue($priceRule->product_id);
                $form->markup->setValue($priceRule->markup);
                $form->priority->setValue($priceRule->priority);
            }
        }
        $this->view->formPriceRule = $form;

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Action for save
     */
    public function saveAction()
    {
        // Initialize price rule form
        $form = new Admin_Model_FormPriceRule(array('languageId' => $this->_languageId));
        $form->setAction('/' . $this->view->language . '/admin/price_rule/save/');

        // Has the priceRule form been posted?
        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getPost();

            // If the submitted data is valid, attempt to save priceRule
            if ($form->isValid($data)) {
                $priceRule = array();
                $priceRule['id'] = $data['id'];
                $priceRule['category_id'] = $data['category'] ? $data['category'] : null;
                $priceRule['manufacturer_id'] = $data['manufacturer'] ? $data['manufacturer'] : null;
                $priceRule['product_id'] = $data['product'];
                $priceRule['markup'] = $data['markup'];
                $priceRule['priority'] = $data['priority'];
                $priceRuleModel = new Admin_Model_PriceRule();
                $priceRuleModel->save($priceRule);
                $this->_redirect('/' . $this->view->language . '/admin/price_rule/index');
            } else {
                $this->view->errors = $form->getErrors();
                $form->id->setValue($data['id']);
                $form->category->setValue($data['category']);
                $form->manufacturer->setValue($data['manufacturer']);
                $form->product->setValue($data['product']);
                $form->markup->setValue($data['markup']);
                $form->priority->setValue($data['priority']);
            }
        }
        $this->view->formPriceRule = $form;
        $this->render('edit');

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

}

